<template lang="pug">
    CreateForm(:config="config_copy" @submit-success="submit_success")
</template>
<script>
import CreateForm from "./create";
import { Message } from "element-ui";
import axios from "../../../plugins/axios";
import UtilMixin from "./util-mixin";

export default {
  name: "simple-maintenace-creaate",
  components: { CreateForm },
  mixins: [UtilMixin],
  data() {
    return {
      config_copy: { action: "", fields: [] }
    };
  },

  props: {
    config: { type: Object }
  },
  computed: {
    primaryKey() {
      return this.$store.state.base.primaryKey;
    },
    id() {
      return this.$store.state.table.editId;
    }
  },

  watch: {
    id() {
      this.readModel();
    }
  },

  methods: {
    readModel() {
      if (!this.id) {
        Message.error("请设置编辑主键值");
        return;
      }

      let data = {};
      data[this.primaryKey] = this.id;
      const options = { url: this.config.readAction, method: "post", data };

      axios(options)
        .then(res => this.dispatch(res))
        .catch(err => Message.error(`获取编辑数据错误:${err.message}`));
    },

    dispatch(model) {
      this.config_copy = JSON.parse(JSON.stringify(this.config));

      for (let key in model) {
        const val = model[key];

        let match = this.config_copy.fields.find(
          field => field.fieldName == key
        );
        if (match == null) continue;

        match.val = val;

        if (match.type == "Image") {
          // 图片
          var mapField = match.mapField;
          if (!mapField) continue;

          match.mapVal = this.getValue(model, match.mapField); // 解析出map的值
        }
      }

      // console.log(this.config_copy);
    },

    submit_success(res) {
      this.$emit("submit-success", res);
    }
  },

  created() {
    this.readModel();
  }
};
</script>
<style lang="less" scoped>
</style>
